/**
 * examples:
 * [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16],
    ]   
    output:[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
 */
var spiraOrder = function (matrix) {
    if (matrix.length === 0) {
        return []
    }
    // 定义边界
    let top = 0
    let bottom = matrix.length - 1
    let left = 0
    let right = matrix[0].length - 1
    // 顺序为右、下、左、上
    let direction = "right"
    let result = []

    while (left <= right && top <= bottom) {
        if (direction === "right") {
            // 一直循环到right那个点
            for (let i = left; i <= right; i++) {
                result.push(matrix[top][i])
            }
            top++
            direction = "down"
        } else if (direction === "down") {
            for (let i = top; i <= bottom; i++) {
                result.push(matrix[i][right])
            }
            right--
            direction = "left"
        } else if (direction === "left") {
            for (let i = right; i >= left; i--) {
                result.push(matrix[bottom][i])
            }
            bottom--
            direction = "up"
        } else if (direction === "top") {
            for (let i = bottom; i >= top; i--) {
                result.push(matrix[i][left])
            }
            left++
            direction = "right"
        }
    }
    
    return result
}